import { defineComponent, h, onMounted, PropType, ref, watch } from 'vue'
import type { Model } from '@antv/x6'
import { Cell, Graph, Node, Path } from '@antv/x6'
// import { useTeleport } from '@antv/x6-vue-shape'
// import { useTeleport } from 'antv-x6-vue-teleport-view'
// import Hierarchy from '@antv/hierarchy'
// import categoryData from '../../data/algorithm-category.json'
import vueShape, { useTeleport } from '@antv/x6-vue-shape'

import './registerNode'
import { getJSONData } from './groupData'
// interface HierarchyResult {
//   id: number
//   x: number
//   y: number
//   children: HierarchyResult[]
// }

const defaultViewId = 'antv-group-teleport-view'


// Graph.registerNode('group-header', {
//   inherit: 'vue-shape',
//   view: defaultViewId,
//   x: 0,
//   y: 0,
//   width: 248,
//   height: 36,
//   component: {
//     render: () => h(SourceNode),
//   },
// })


// 这个是为了提升自定义节点渲染性能的
const TeleportContainer = useTeleport(defaultViewId)

export default defineComponent({
  name: 'ModelGraph',
  inject: ["getGraph", "getNode"],
  props: {
    sourceList: {
      type: Object as PropType<any>,
      default: () => []
    },
    targetList: {
      type: Object as PropType<any>,
      default: () => []
    }
  },
  emits: ['bindDimension', 'revise', 'unbind'],
  setup: (props, { slots, attrs, emit }) => {
    const domRef = ref()
    // todo: 是否需要 ref
    const graphContext = ref()

    const initGraph = () => {
      if (domRef.value && !graphContext.value) {
        graphContext.value = new Graph({
          container: domRef.value,
          grid: {
            size: 10,
            visible: true,
            type: 'dot', // 'dot' | 'fixedDot' | 'mesh'
            args: {
              color: '#a05410', // 网格线/点颜色
              thickness: 1, // 网格线宽度/网格点大小
            },
          },
          interacting: {
            nodeMovable: false,
          },
          panning: {
            enabled: true,
            eventTypes: ['leftMouseDown', 'mouseWheel'],
          },
          mousewheel: {
            enabled: true,
            modifiers: 'ctrl',
            factor: 1.1,
            maxScale: 1.5,
            minScale: 0.5,
          },
        })
        // const datajosn = getJSONData()
        // graphContext.value.fromJSON(datajosn)
        graphContext.value.on('edge:mouseenter', ({ edge }: any) => {
          const targetCell = graphContext.value.getCellById(edge.target.cell)
          const edges = graphContext.value.getIncomingEdges(targetCell);
          edges.map((e: any) => {
            const sourceCell = graphContext.value.getCellById(e.source.cell)
            sourceCell.setData({isActive: true})
            e.attr(
              {
                line: {
                  stroke: '#396EFE',
                  strokeWidth: 1,
                  strokeDasharray: 0,
                  sourceMarker: {
                    name: 'circle',
                    fill: '#396EFE',
                    r: 3,
                  },
                  targetMarker: {
                    name: 'circle',
                    fill: '#396EFE',
                    r: 3,
                  },
                },
              }
            )
          })
          targetCell.setData({isActive: true})
        })
        graphContext.value.on('edge:mouseleave', ({ edge }: any) => {
          const targetCell = graphContext.value.getCellById(edge.target.cell)
          const edges = graphContext.value.getIncomingEdges(targetCell);
          edges.map((e: any) => {
            const sourceCell = graphContext.value.getCellById(e.source.cell)
            sourceCell.setData({isActive: false})
            e.attr(
              {
                line: {
                  stroke: '#9098A9',
                  strokeWidth: 0.5,
                  strokeDasharray: 5,
                  sourceMarker: {
                    name: 'circle',
                    fill: '#fff',
                    r: 3,
                  },
                  targetMarker: {
                    name: 'circle',
                    fill: '#fff',
                    r: 3,
                  },
                },
              }
            )
          })
          targetCell.setData({isActive: false})
        })
        const models = getJSONData(props.sourceList, props.targetList, {onBindDimension, onRevise, onUnbind});
        if (graphContext.value) {
          setTimeout(() => {
            graphContext.value.fromJSON(models)
          }, 400)
        }
      }
    }
    onMounted(() => {
      initGraph()
    })
    watch(() => props.targetList, () => {
      if (props.sourceList && props.targetList) {
        const models = getJSONData(props.sourceList, props.targetList, {onBindDimension, onRevise, onUnbind});
        if (graphContext.value) {
          setTimeout(() => {
            graphContext.value.fromJSON(models)
          }, 400)
        }
      }
    })
    watch(() => props.sourceList, () => {
      if (props.sourceList && props.targetList) {
        const models = getJSONData(props.sourceList, props.targetList, {onBindDimension, onRevise, onUnbind});
        if (graphContext.value) {
          // graphContext.value.clearCells();
          setTimeout(() => {
            graphContext.value.fromJSON(models)
            // graphContext.value.centerPoint(280, models?.nodes?.[0]?.y)
            // graphContext.value.positionContent('left')
            // graphContext.value.positionPoint({ x: models?.nodes?.[0]?.x, y: models?.nodes?.[0]?.y }, 10, '50%')
          }, 400)
        }
      }
    })
    const onBindDimension = (data: any) => {
      console.log('点击了绑定')
      emit('bindDimension', data)
    }
    const onRevise = (data: any) => {
      emit('revise', data)
    }
    const onUnbind = (data: any) => {
      emit('unbind', data)
    }
    return () => {
      return (
        <>
        <TeleportContainer />
        <div ref={domRef} style={{ flex: 1, width: '100%', height: '100%' }}></div>
      </>
      )
    }
  },
})
